package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.Advice.LeaseException;
import com.atguigu.lease.common.constants.RedisConstant;
import com.atguigu.lease.common.jwt.JwtUtil;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.jsonwebtoken.Claims;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SystemUserService systemUserService;

    @Override
    public CaptchaVo getCaptcha() {
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);//创建验证码对象并设置参数
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);//设置验证码类型
        String base64 = specCaptcha.toBase64();//获取验证码图片的base64编码
        String text = specCaptcha.text();//获取验证码文本
        String uuidKey = RedisConstant.ADMIN_LOGIN_PREFIX+
                UUID.randomUUID().toString().replaceAll("-", "");//生成随机key要作为验证码的key
        redisTemplate.opsForValue().set(uuidKey, text, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);//保存验证码
        CaptchaVo captchaVo = new CaptchaVo(base64, uuidKey);//封装验证码对象
        return captchaVo;
    }

    @Override
    public String login(LoginVo loginVo) {
        String redisCaptcha = (String) redisTemplate.opsForValue().get(loginVo.getCaptchaKey());//获取redis中的验证码
        if (ObjectUtils.isEmpty(redisCaptcha))//判断验证码是否删除
        {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        if (!redisCaptcha.equalsIgnoreCase(loginVo.getCaptchaCode()))//判断验证码是否一致
        {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        // 查询用户是否存在
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getUsername, loginVo.getUsername());//查询用户名
        SystemUser systemUser = systemUserService.getOne(queryWrapper);
        if (systemUser == null) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        // 判断密码是否一致
        String s = DigestUtils.md5Hex(loginVo.getPassword());//获取输入的密码并加密
        if (!systemUser.getPassword().equals(s))//判断密码是否一致
        {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //判断账号是否可用
        if (systemUser.getStatus()== BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        // 生成token
        String token = JwtUtil.createToken(systemUser.getId(), systemUser.getUsername());//生成token
        return token;
    }

    @Override
    public SystemUserInfoVo systemUserInfo(String token) {
        Claims claims = JwtUtil.parseToken(token);//解析token获取claims
        Integer userId  = (Integer) claims.get("userId");//获取用户id
        SystemUser systemUser = systemUserService.getById(userId);//获取用户信息
        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();//创建用户信息对象
        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }


}
